package com.pengshun.modules.api.pay.service;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import java.io.StringReader;
import java.util.Collection;

/**
 * @author luoligang
 */
public class JaxbUtil {

    private JAXBContext jaxbContext;

    public JaxbUtil(Class<?>... types) {
        try {
            jaxbContext = JAXBContext.newInstance(types);
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }

    public <T> T fromXml(String xml) {
        try {
            XMLInputFactory xif = XMLInputFactory.newInstance();
            xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES,false);
            xif.setProperty(XMLInputFactory.SUPPORT_DTD,true);
            XMLStreamReader xsr = xif.createXMLStreamReader(new StringReader(xml));
            return (T) createUnmarshaller().unmarshal(xsr);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public Unmarshaller createUnmarshaller() {
        try {
            return jaxbContext.createUnmarshaller();
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }

    public static class CollectionWrapper {
        @XmlAnyElement
        protected Collection collection;
        }
}
